import { Directive, DirectiveBinding } from "vue";
import { useUserInfoStore} from '@/stores/userInfo';

function checkPermission(el: HTMLElement, binding: DirectiveBinding) {
  const { value } = binding;
  if (!value) {
    console.error('v-btnPermission 指令缺少权限参数');
    return;
  }
  const userStore = useUserInfoStore();
  const permissions = userStore.btnPermissions; 
  let hasAuth = false;
  if (typeof value === 'string') {
    hasAuth = permissions.includes(value);
  } else if (Array.isArray(value)) {
    hasAuth = value.some((perm) => permissions.includes(perm));
  } else {
    console.error('v-btnPermission 指令绑定值必须是字符串或数组');
    return;
  }
  if (!hasAuth) {
    // 存储元素原始display值
    if(!el.dataset.originalDisplay) {
      el.dataset.originalDisplay = el.style.display;
    }
    el.style.display = 'none';
  } else {
    // 如果有权限，恢复原始display
    el.style.display = el.dataset.originalDisplay || '';
  }
}
const btnPermission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  }
}
export default btnPermission